Maintaining the Heap Property: The Sift Operations
The core of efficient heap management relies on the Heapify process, which restores the structural integrity after modification (insertion or extraction).
1. Sift Down (Key to Extraction)
When an element violates the Max-Heap property (it is smaller than its children), we use Sift Down (or sink) to push it to its correct position:
- Compare the current node () with its largest child ().
- If , swap and .
- Repeat the process recursively on the new position of .
This process moves the violation down the tree until the property is satisfied or the element reaches a leaf node.
2. Sift Up (Key to Insertion)
When a new element is added to the end of the array (leaf node), Sift Up (or bubble) compares it with its parent and swaps upward until the Max-Heap property is restored.
Key Operation: Extract Max ()
The Extract Max operation is fundamental for Priority Queue implementation, always retrieving the highest priority item (the root) and ensuring the heap property is immediately restored.
Steps for Extraction:
- Swap: Swap the root (`Heap[0]`, the Max element) with the last element (`Heap[N-1]`).
- Remove: Decrease the effective size of the heap by 1 (removing the original Max value).
- Restore: Execute the `Sift Down` operation starting at the new `Heap[0]` to move the misplaced element down to its correct, ordered position.
Time Complexity of Heap Operations (Max-Heap)
| Operation | Description | Time Complexity | Notes |
|---|---|---|---|
| Peek (Find Max) | Look at the root element. | Direct array access. | |
| Insert | Add element, then Sift Up. | Height of the tree determines swaps. | |
| Extract Max | Swap, remove, then Sift Down. | Dominated by the Sift Down operation. | |
| Build Heap | Heapify an entire array in place. | Efficient linear time creation. |
1. An `Extract Max` operation on a Max-Heap involves three primary steps: swapping the root with the last element, removing the last element, and performing `Sift Down` on the new root. Which step dictates the overall complexity?
2. When a new element is inserted into a Max-Heap, which operation is used to restore the heap property?
3. What is the time complexity of building a heap from an unsorted array of N elements using the efficient `BuildHeap` algorithm?